package com.example.pt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.pt.dto.UserTransferStatsDTO;
import com.example.pt.entity.UserTransferStats;
import com.example.pt.mapper.UserTransferStatsMapper;
import com.example.pt.service.UserTransferStatsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;

@Service
public class UserTransferStatsServiceImpl extends ServiceImpl<UserTransferStatsMapper, UserTransferStats> implements UserTransferStatsService {
    
    private static final Logger logger = LoggerFactory.getLogger(UserTransferStatsServiceImpl.class);
    @Autowired
    private PromotionServiceImpl promotionService;

    @Override
    @Transactional
    public boolean updateUserTransferStats(UserTransferStats stats) {
        if (stats == null || stats.getUserId() == null || stats.getInfoHash() == null) {
            return false;
        }
        String infohash = stats.getInfoHash();
        
        // 设置更新时间
        stats.setLastUpdated(System.currentTimeMillis());
        
        // 查询是否已存在记录
        UserTransferStats existingStats = getStatsByUserAndInfoHash(stats.getUserId(), stats.getInfoHash());
        
        if (existingStats != null) {
            logger.debug("找到现有记录: 用户={}, 种子={}, 原上传量={}, 原下载量={}, 新上传量={}, 新下载量={}",
                stats.getUserId(), stats.getInfoHash(), 
                existingStats.getUploaded(), existingStats.getDownloaded(),
                stats.getUploaded(), stats.getDownloaded());
            
            // 只有当新值大于旧值时才更新（防止客户端重启等异常情况）
            if (stats.getUploaded() > existingStats.getUploaded()) {
                existingStats.setUploaded(stats.getUploaded());
                existingStats.setVirtual_uploaded(stats.getUploaded());
                logger.info("更新用户上传量: userId={}, infoHash={}, uploaded={}",
                    stats.getUserId(), stats.getInfoHash(), stats.getUploaded());
            }
            
            if (stats.getDownloaded() > existingStats.getDownloaded()) {
                existingStats.setDownloaded(stats.getDownloaded());
                double rate = promotionService.getCurrentPromotionsByInfoHash(infohash);
                existingStats.setVirtual_uploaded((long)(stats.getDownloaded()*rate));
                logger.info("更新用户下载量: userId={}, infoHash={}, downloaded={}",
                    stats.getUserId(), stats.getInfoHash(), stats.getDownloaded());
            }
            
            // 更新其他非统计字段
            existingStats.setPeerIp(stats.getPeerIp());
            existingStats.setPeerPort(stats.getPeerPort());
            existingStats.setPeerId(stats.getPeerId());
            existingStats.setLastUpdated(stats.getLastUpdated());
            
            return updateById(existingStats);
        } else {
            // 不存在记录，新增
            logger.info("创建新记录: 用户={}, 种子={}, 上传量={}, 下载量={}",
                stats.getUserId(), stats.getInfoHash(), stats.getUploaded(), stats.getDownloaded());
            
            return save(stats);
        }
    }

    @Override
    public UserTransferStats getStatsByUserAndInfoHash(Integer userId, String infoHash) {
        LambdaQueryWrapper<UserTransferStats> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserTransferStats::getUserId, userId)
                .eq(UserTransferStats::getInfoHash, infoHash);
        return getOne(queryWrapper);
    }
    
    @Override
    public UserTransferStatsDTO getUserTotalTransferStats(Integer userId) {
        if (userId == null) {
            logger.warn("获取用户传输统计数据失败：用户ID为空");
            return new UserTransferStatsDTO();
        }
        
        try {
            // 使用Mapper方法直接查询总上传量、总下载量、总虚拟上传量和总虚拟下载量
            Map<String, Object> statsMap = baseMapper.getUserTotalTransferStats(userId);
            
            // 处理BigDecimal类型
            BigDecimal uploadedDecimal = (BigDecimal) statsMap.get("totalUploaded");
            BigDecimal downloadedDecimal = (BigDecimal) statsMap.get("totalDownloaded");
            BigDecimal virtualUploadedDecimal = (BigDecimal) statsMap.get("totalVirtualUploaded");
            BigDecimal virtualDownloadedDecimal = (BigDecimal) statsMap.get("totalVirtualDownloaded");
            
            Long totalUploaded = uploadedDecimal != null ? uploadedDecimal.longValue() : 0L;
            Long totalDownloaded = downloadedDecimal != null ? downloadedDecimal.longValue() : 0L;
            Long totalVirtualUploaded = virtualUploadedDecimal != null ? virtualUploadedDecimal.longValue() : 0L;
            Long totalVirtualDownloaded = virtualDownloadedDecimal != null ? virtualDownloadedDecimal.longValue() : 0L;
            
            logger.info("用户 {} 总上传量: {}, 总下载量: {}, 总虚拟上传量: {}, 总虚拟下载量: {}", 
                userId, totalUploaded, totalDownloaded, totalVirtualUploaded, totalVirtualDownloaded);
            
            return new UserTransferStatsDTO(userId, totalUploaded, totalDownloaded, 
                                          totalVirtualUploaded, totalVirtualDownloaded);
        } catch (Exception e) {
            logger.error("获取用户 {} 传输统计数据失败", userId, e);
            return new UserTransferStatsDTO(userId, 0L, 0L, 0L, 0L);
        }
    }
} 